﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Notes.Resources;
using System.IO;
using System.Diagnostics;
using System.Threading;

using Microsoft.Phone.Notification;
using Microsoft.Phone.Tasks;
using System.Xml.Serialization;
using NotesAgent;

namespace Notes
{
    public partial class MainPage : PhoneApplicationPage
    {



        public int MAX_SECONDS = 60;
        public int remainingSeconds = 0;
        public Timer timer;
        public static List<Ads> ads;
        public static Account currentAccount = new Account();

        bool working = false;
        public MainPage()
        {
            /// Holds the push channel that is created or found.

            PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
            InitializeComponent();
            DataContext = App.ViewModel;
            Ads_List.DataContext = App.ViewModel;
            try
            {
                var occ = Storage.LoadUtilizations() + 1;
                new Thread(new ThreadStart(() =>
                {
                    Storage.getHTML(Storage.GetUtilizationUrl(occ, App.isTrial(), Strings.Title),
                        (s) =>
                        {
                            Storage.DeleteUtilizations();
                        },
                        () =>
                        {
                            Storage.SaveUtilizations(occ);
                        });
                })).Start();
            }
            catch { }



            ads = Storage.LoadAds();
            App.ViewModel.Ads.Clear();
            for (int i = 0; i < ads.Count; i++)
                App.ViewModel.Ads.Add(new AdsViewModel()
                {
                    ID = ads[i].ID,
                    Description = ads[i].Description,
                    ImageUri = new Uri(ads[i].ImageUrl, UriKind.RelativeOrAbsolute),
                    Name = ads[i].Name
                }
                    );
            currentAccount = Storage.LoadAccount();

            UpdateAds();


            SetElements();

            BuildApplicationBar(currentAccount != null && currentAccount.username != "");

            working = false;
            if (currentAccount.IsActive())
                BeginUpdate();
            else
                working = false;
            

            if (Storage.IsFirstOpening())
            {
                MessageBox.Show(Strings.Disclaimer_Once);
                Storage.SetAlreadyOpened();
            }
        }
        public static bool skip_update = false;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (working || skip_update)
                return;
            currentAccount = Storage.LoadAccount();
            if (currentAccount.IsActive())
                BeginUpdate();
        }
        public void BuildApplicationBar(bool completed)
        {
            ApplicationBar.Buttons.Clear();
            ApplicationBarIconButton credits = new ApplicationBarIconButton() { Text = Strings.Credits, IsEnabled = true };
            if (App.CurrentTheme == App.Theme.Dark)
                credits.IconUri = new Uri("\\Images\\dark\\appbar.questionmark.rest.png", UriKind.Relative);
            else
                credits.IconUri = new Uri("\\Images\\light\\appbar.questionmark.rest.png", UriKind.Relative);
            credits.Click += OpenCredits_Button_Click;

            ApplicationBar.Buttons.Add(credits);
            ApplicationBarIconButton check = new ApplicationBarIconButton() { Text = Strings.Login, IsEnabled = true };
            if (App.CurrentTheme == App.Theme.Dark)
                check.IconUri = new Uri("\\Images\\dark\\appbar.check.rest.png", UriKind.Relative);
            else
                check.IconUri = new Uri("\\Images\\light\\appbar.check.rest.png", UriKind.Relative);
            check.Click += Check_Button_Click;
            ApplicationBar.Buttons.Add(check);
        }
        public void UpdateAds()
        {

            try
            {

                var url = "http://fboscari.altervista.org/GetAds.php?name=" + Strings.Title + "&lang=" + Strings.Lang;
                Storage.getHTML(url,
                    s =>
                    {
                        AdsParser parser = new AdsParser(s);
                        var newList = parser.getAds();
                        if (newList.Count <= 0)
                            return;
                        ads = newList;
                        Dispatcher.BeginInvoke(() =>
                        {
                            Storage.SaveAds(ads);
                            App.ViewModel.Ads.Clear();
                            for (int i = 0; i < ads.Count; i++)
                                App.ViewModel.Ads.Add(new AdsViewModel()
                                {
                                    ID = ads[i].ID,
                                    Description = ads[i].Description,
                                    ImageUri = new Uri(ads[i].ImageUrl, UriKind.RelativeOrAbsolute),
                                    Name = ads[i].Name
                                });
                        });
                    },
                    () =>
                    {

                    });

            }
            catch { }
        }

        

        private void OpenCredits_Button_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/CreditsPage.xaml", UriKind.Relative));
        }


        public void SetElements()
        {
            ApplicationBar.IsVisible = true;
            //PageTitle.Text = Strings.Title;
            Username_Text.Visibility = System.Windows.Visibility.Visible;
            Username_Area.Visibility = System.Windows.Visibility.Visible;
            Password_Text.Visibility = System.Windows.Visibility.Visible;
            Password_Area.Visibility = System.Windows.Visibility.Visible;
            CheckUserPassword_Button.Visibility = System.Windows.Visibility.Visible;

            CancelUpdate_Button.Visibility = System.Windows.Visibility.Collapsed;
            //Current_Step_Label.Visibility = System.Windows.Visibility.Collapsed;
            RemainingTime_Label.Visibility = System.Windows.Visibility.Collapsed;
            RecoverPassword_Button.Visibility = System.Windows.Visibility.Visible;
            CreateAccount_Button.Visibility = System.Windows.Visibility.Visible;
            //if (!working)
            //{
            //    Username_Area.Text = currentAccount.username;
            //    Password_Area.Password = currentAccount.password;
            //}
            SaveAccount_Switch.Visibility = System.Windows.Visibility.Visible;
            if (currentAccount.IsActive())
            {
                ApplicationBar.IsVisible = true;
                Username_Area.Text = currentAccount.username;
                Password_Area.Password = currentAccount.password;

                SaveAccount_Switch.IsChecked = currentAccount.IsActive();
            }
            else
            {
                SaveAccount_Switch.IsChecked = false;
            }
            
        }

        public void ToggleOverlay(bool isOpen)
        {
            working = isOpen;
            if (isOpen)
            {
                //PageTitle.Text = Strings.Working;
                //Current_Step_Label.Visibility = System.Windows.Visibility.Visible;
                CancelUpdate_Button.Visibility = System.Windows.Visibility.Visible;
                RemainingTime_Label.Visibility = System.Windows.Visibility.Visible;
                EnableProgressBar();
                ApplicationBar.IsVisible = false;
                CheckUserPassword_Button.Visibility = System.Windows.Visibility.Collapsed;

                Username_Text.Visibility = System.Windows.Visibility.Collapsed;
                Username_Area.Visibility = System.Windows.Visibility.Collapsed;
                Password_Text.Visibility = System.Windows.Visibility.Collapsed;
                Password_Area.Visibility = System.Windows.Visibility.Collapsed;

                SaveAccount_Switch.Visibility = System.Windows.Visibility.Collapsed;

                RecoverPassword_Button.Visibility = System.Windows.Visibility.Collapsed;
                CreateAccount_Button.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                DisableProgressBar();
                SetElements();
            }
            
        }


        public void OnError(string message)
        {
            Dispatcher.BeginInvoke(() =>
            {

                Password_Area.IsEnabled = true;
                Username_Area.IsEnabled = true;
                working = false;
                ToggleOverlay(false);
                working = false;
                DisableProgressBar();
                MessageBox.Show(message);

            });
        }

        private void Timer_Callback(object o)
        {
            if (!working)
            {
                timer.Dispose();
                timer = null;
            }
            remainingSeconds--;
            if (remainingSeconds <= 0)
            {
                working = false;
                timer.Dispose();
                timer = null;
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(Strings.ConnectionError);
                    CancelUpdate_Button_Click(null, null);
                });
            }
            else
                Dispatcher.BeginInvoke(() =>
                {
                    RemainingTime_Label.Text = Strings.RemainingTime + remainingSeconds + " s.";
                });
        }

        public void BeginUpdate()
        {
            if (currentAccount == null)
                return;
            if (timer != null)
                timer.Dispose();
            timer = new Timer(new TimerCallback(Timer_Callback), null, 0, 1000);
            remainingSeconds = MAX_SECONDS;
            ToggleOverlay(true);
            currentAccount.username = Username_Area.Text;
            currentAccount.password = Password_Area.Password;
            UpdateTile();
        }

        public void UpdateTile()
        {

            string url = "http://fboscari.altervista.org/Notes/get_notes_phone.php?";
            //url += Utils.GetUpdateLiveTileArgs(result, currentAccount.contract, currentAccount.username, currentAccount.password, currentAccount.number, currentAccount.showDate);
            url += "username=" + currentAccount.username + "&pwd=" + currentAccount.password
                + "&isTrial=" + App.isTrial()
                + "&salt=" + DateTime.Now.Millisecond;
            var temp_account = new Account(){
                username=Username_Area.Text,
                password = Password_Area.Password
            };
            ScheduledAgent.GetResult(temp_account, result =>
            {
                Dispatcher.BeginInvoke(() =>
                {
                    ToggleOverlay(false);
                    currentAccount.username = Username_Area.Text;
                    currentAccount.password = Password_Area.Password;
                    currentAccount.active = false;
                    if (SaveAccount_Switch.IsChecked.Value)
                    {
                        currentAccount.active = true;
                        Storage.SaveAccount(currentAccount);
                    }
                    else
                        Storage.DeleteAccount();
                    if (result == null)
                    {
                        //ToggleOverlay(false);
                        return;
                    }
                    result.UpdateChars();
                    if (result.err == "0")
                    {
                        Storage.SaveResult(result);
                        NotesPage.result = result;
                        NavigationService.Navigate(new Uri("/NotesPage.xaml", UriKind.RelativeOrAbsolute));

                    }
                    else if (result.err == "1")
                    {
                        MessageBox.Show(Strings.UnknownEmail);

                    }
                    else if (result.err == "2")
                    {
                        MessageBox.Show(Strings.WrongPassword);

                    }
                    else
                    {
                        MessageBox.Show(Strings.GeneralError);

                    }

                });
            },
            () =>
            {
                OnError(Strings.ConnectionError);

            });

            //Storage.getHTML(url, s =>
            //{
            //    Dispatcher.BeginInvoke(() =>
            //    {
            //        ToggleOverlay(false);
            //        currentAccount.username = Username_Area.Text;
            //        currentAccount.password = Password_Area.Password;
            //        currentAccount.active = false;
            //        if (SaveAccount_Switch.IsChecked.Value)
            //        {
            //            currentAccount.active = true;
            //            Storage.SaveAccount(currentAccount);   
            //        }
            //        else
            //            Storage.DeleteAccount();
                    
            //        XmlSerializer serializer = new XmlSerializer(typeof(Result));
            //        var reader = new StringReader(s);
            //        Result result = serializer.Deserialize(reader) as Result;

            //        if (result == null)
            //        {
            //            //ToggleOverlay(false);
            //            return;
            //        }
            //        result.UpdateChars();
            //        if (result.err == "0")
            //        {
            //            NotesPage.result = result;
            //            NavigationService.Navigate(new Uri("/NotesPage.xaml", UriKind.RelativeOrAbsolute));
    
            //        }
            //        else if (result.err == "1")
            //        {
            //            MessageBox.Show(Strings.UnknownEmail);
               
            //        }
            //        else if (result.err == "2")
            //        {
            //            MessageBox.Show(Strings.WrongPassword);
                  
            //        }
            //        else
            //        {
            //            MessageBox.Show(Strings.GeneralError);
                   
            //        }
                    
            //    });
            //},
            //(e) =>
            //{
            //    OnError(Strings.ConnectionError);

            //});
        }

        private void Check_Button_Click(object sender, EventArgs e)
        {
            CheckUserPassword_Button_Click(null, null);
        }

        private void CheckUserPassword_Button_Click(object sender, RoutedEventArgs e)
        {
            //Username_Area.Text = "gmrfcb";
            //Password_Area.Password = "gmrfcb";
            working = true;
            //Password_Area.IsEnabled = false;
            //Username_Area.IsEnabled = false;

            if (Username_Area.Text == "" || Password_Area.Password == "")
            {
                OnError(Strings.MissingData);
                return;
            }
            ApplicationBar.IsVisible = false;
            SaveAccount_Switch.Visibility = System.Windows.Visibility.Collapsed;

            //CheckUserPassword_Button.IsEnabled = false;
            EnableProgressBar();

            BeginUpdate();
        }
        private void Username_Area_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (Username_Area.Text != "")
                    if (Password_Area.Password != "")
                    {
                        CheckUserPassword_Button.Focus();
                        CheckUserPassword_Button_Click(null, null);

                    }
                    else
                        Password_Area.Focus();
            }
        }

        private void Password_Area_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (Password_Area.Password != "")
                    if (Username_Area.Text != "")
                    {
                        CheckUserPassword_Button.Focus();
                        CheckUserPassword_Button_Click(null, null);
                    }
                    else
                        Username_Area.Focus();
            }

        }

        private void EnableProgressBar()
        {
            Dispatcher.BeginInvoke(() =>
            {
                ToggleProgressBar.IsEnabled = true;
                ToggleProgressBar.IsIndeterminate = true;
                ToggleProgressBar.Visibility = System.Windows.Visibility.Visible;
            });
        }
        private void DisableProgressBar()
        {
            Dispatcher.BeginInvoke(() =>
            {
                ToggleProgressBar.IsEnabled = false;
                ToggleProgressBar.IsIndeterminate = false;
                ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
            });
        }

        private void CancelUpdate_Button_Click(object sender, RoutedEventArgs e)
        {
            ToggleOverlay(false);
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            

            if (working)
            {
                CancelUpdate_Button_Click(null, null);
                e.Cancel = true;
            }
            //else
            //{

            //    if (currentAccount.username != "" && currentAccount.password != "")
            //        if (MessageBox.Show(Strings.SaveAccount, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            //        {
            //            //ToggleOverlay(true);
            //            SendAccountData(false);

            //            Storage.SaveAccount(currentAccount);
            //            Thread.Sleep(2000);
            //        }
            //}
        }


        private void CreateAccount_Button_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/NewAccountPage.xaml", UriKind.RelativeOrAbsolute));
        }



        private void Ads_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Ads_List.SelectedItem == null)
                return;
            AdsViewModel ads = Ads_List.SelectedItem as AdsViewModel;
            Ads_List.SelectedItem = null;
            if (ads.Name != Strings.OtherProducts && ads.ID != "")
                OpenMarket(ads.ID);


        }
        private void OpenMarket(string ID)
        {

            MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
            marketplaceDetailTask.ContentIdentifier = ID;
            marketplaceDetailTask.Show();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        private void SaveAccount_Switch_Unchecked(object sender, RoutedEventArgs e)
        {

        }

        private void SaveAccount_Switch_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void RecoverPassword_Button_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/RecoverPasswordPage.xaml", UriKind.RelativeOrAbsolute));
        }
    }


}